package xin.petstore.framework.file.hash;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;

public abstract class HashCalc
        implements IHashCalc {
    private static final char[] hexDigits = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public static HashCalc getStreamInstance(InputStream inputStream, String[] algorithms) {
        try {
            return new StreamHashCalc(inputStream, algorithms);
        } catch (NoSuchAlgorithmException ex) {
            throw translateException(ex);
        }

    }

    public static HashCalc getFileInstance(File file, String[] algorithms) {
        try {
            return new FileHashCalc(file, algorithms);
        } catch (NoSuchAlgorithmException ex) {
            throw translateException(ex);
        } catch (FileNotFoundException ex) {
            throw translateException(ex);
        }
    }

    public static HashCalc getFileInstance(String fileName, String[] algorithms) {
        try {
            return new FileHashCalc(fileName, algorithms);
        } catch (NoSuchAlgorithmException ex) {
            throw translateException(ex);
        } catch (FileNotFoundException ex) {
            throw translateException(ex);
        }
    }

    private static IllegalArgumentException translateException(Exception ex) {
        return new IllegalArgumentException(ex);
    }

    protected static String bufferToHex(byte[] bytes) {
        StringBuffer stringbuffer = new StringBuffer(2 * bytes.length);
        for (int idx = 0; idx < bytes.length; idx++) {
            char c0 = hexDigits[((bytes[idx] & 0xF0) >> 4)];
            char c1 = hexDigits[(bytes[idx] & 0xF)];
            stringbuffer.append(c0);
            stringbuffer.append(c1);
        }
        return stringbuffer.toString();
    }
}

